<?php
            
use app\model\Record; 
use app\model\Theme; 


/**
 * Author: cbw
 * Desc: 易宣优惠券
 * Time: 2022/11/2 15:40
 * Email: 17854288794@163.com
 */
require_once PATH_MODULE .'define.php';
class CouponModel extends PluginModel {

    /**
     * Desc:获取优惠券的类型数组
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 14:56
     * @param string $key
     * @return array[]
     */
    public static function couponTypeArrByKey($key='target')
    {
        //身份限制
        if ($key=='target'){
            return [
                ['title'=>'不限','value'=>1],
                ['title'=>'团长','value'=>2],
                ['title'=>'团员','value'=>3],
            ];
        }
        //时间限制
        if ($key=='show_type'){
            return [
                ['title'=>'不限','value'=>1],
                ['title'=>'时间范围限制','value'=>2],
            ];
        }
        //预售模式
        if ($key=='used_type'){
            return [
                ['title'=>'不限','value'=>1],
                ['title'=>'定金','value'=>2],
                ['title'=>'补款','value'=>3],
                ['title'=>'全款','value'=>4],
                ['title'=>'补款+全款','value'=>5],
            ];
        }
        //领取方式
        if ($key=='get_type'){
            return [
                ['title'=>'点击领取','value'=>1],
                ['title'=>'定金支付后自动发放','value'=>2],
            ];
        }
        //优惠券状态
        if ($key=='status'){
            return [
                ['title'=>'启用','value'=>1],
                ['title'=>'禁用','value'=>2],
                ['title'=>'过期','value'=>3],
            ];
        }
        //用户优惠券记录
        if ($key=='user_flag_status'){
            return [
                ['title'=>'未使用','value'=>1],
                ['title'=>'已使用','value'=>2],
                ['title'=>'已失效','value'=>3],
            ];
        }
    }

    /**
     * Desc:新增或者修改优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 15:01
     * @param int $coupon_id
     * @param array $data
     * @param array $where
     * @return mixed
     */
    public static function couponEditItem($coupon_id=0,$data=[],$where=[])
    {
        if (!$coupon_id){
            $item = $insertid = db_insert(t_yx_coupon,$data);
        }else{
            $item = db_update(t_yx_coupon,$data,$where);
        }
        return $item;
    }

    /**
     * Desc:更新优惠券库存以及领取数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/6 14:15
     * @param $themeid
     * @param $coupon_id
     */
    public static function couponSubQtyAndAddGetNum($themeid,$coupon_id)
    {
        $coupon_item = self::couponCheckById($themeid,$coupon_id,true);
        $now_time = date("Y-m-d H:i:s",time());
        if ($coupon_item['get_status']==2 && $coupon_item['get_end_time']<$now_time){
            //
            //更新优惠券状态
            $data=['status'=>3];
            $where=['themeid'=>$themeid];
            $update_item= self::couponEditItem($coupon_id,$data,$where);
        }
        $new_qty = $coupon_item['qty']-1>0?$coupon_item['qty']-1:0;
        $data =['qty'=>$new_qty,'get_num'=>$coupon_item['get_num']+1];
        $update_coupon_item = self::couponEditItem($coupon_id,$data,['themeid'=>$themeid,'id'=>$coupon_id]);
    }

    /**
     * Desc:获取优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 18:43
     * @param $themeid
     * @param $coupon_id
     * @param false $is_admin
     * @return array|array[]
     */
    public static function couponCheckById($themeid,$coupon_id,$is_admin=false)
    {
        $item = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$coupon_id]);
        if (!$is_admin){
            if (!$item){
                return ['msg'=>'优惠券不存在','code'=>0];
            }else{
                //判断能否领取
                //判断能否使用
                //判断状态
                $now_time=date("Y-m-d H:i:s",time());
                $status = $item['status'];
                if ($item['get_status']==2 && $now_time>$item['get_end_time']){
                    //更新优惠券状态
                    $data=['status'=>3];
                    $where=['themeid'=>$themeid];
                    $update_item= self::couponEditItem($coupon_id,$data,$where);
                    yxlog('优惠券id:'.$coupon_id.';优惠券信息:过期');
                    return  ['msg'=>'优惠券发放过期','code'=>0];
                }
                if ($item['qty']<1){
                    $data=['status'=>2];
                    $where=['themeid'=>$themeid];
                    $update_item= self::couponEditItem($coupon_id,$data,$where);
                    yxlog('优惠券id:'.$coupon_id.';优惠券信息:库存不足');
                    return  ['msg'=>'优惠券库存不足','code'=>0];
                }

                if ($status!=1){
                    yxlog('优惠券id:'.$coupon_id.';优惠券信息:失效或过期');
                    return ['msg'=>'优惠券失效','code'=>0];
                }

                return ['msg'=>'ok','code'=>1,'item'=>$item];
            }
        }
        return $item;
    }

    /**
     * Desc:获取当前数据或者数据和
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 19:59
     * @param $themeid
     * @param int $target
     * @param int $show_type
     * @param int $used_type
     * @param int $shangjiaid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param false $count
     * @return int
     */
    public static function couponListData($themeid,$target=0,$show_type=0,$used_type=0,$get_type=0,$status=0,$shangjiaid=0,$search='',$page_start=0,
                                          $page_size=10,$start_day='',$end_day='',$count = false)
    {
        $condition="";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($target){
            $condition .= " and a.target=$target ";
        }
        if ($get_type){
            $condition .= " and a.get_type=$get_type ";
        }
        if ($show_type){
            $condition .= " and a.show_type=$show_type ";
        }
        if ($used_type){
            $condition .= " and a.used_type=$used_type ";
        }
        if ($search){
            $condition .= " AND a.name LIKE '".$search."'";
        }
        if ($status){
            $condition .= " and a.status=$status ";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
//            $condition .= "  and a.get_start_time between '".$start_day."' and '".$end_day."'";
//            $condition .= "  or a.get_end_time between '".$start_day."' and '".$end_day."'";
        }
        $condition .= " ORDER BY a.id DESC ";
        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql= " from ".tablename(t_yx_coupon)." as a ".
        " left join ".tablename(t_shangjia)." as c on  a.shangjiaid=c.id ".
        " where a.themeid=$themeid ".$condition;
        if ($count){
            return (int)db_fetchcolumn('SELECT COUNT(*)'.$sql);
        }else{
            $sql= " select a.*,c.name as shangjia_name  ".$sql;
            return db_select($sql);
        }
    }

    /**
     * Desc:订单中选择优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/23 14:14
     * @param $themeid
     * @param $config
     * @return array
     */
    public static function formatCouponList($themeid,$config)
    {
        $list = self::couponListData($themeid,0,0,0,0,1,0,'',0,0,'','');
        $arr = [];
        if ($list){
            foreach ($list as $k => $v)
            {
                if ($config['coupon_use_type']==3){
                    //阶梯优惠券
                    $item_price_arr = json_decode($v['price_info'],true);
                    if ($item_price_arr){
                        foreach ($item_price_arr as $kk => $vv){
                            $tmp_arr = [
                                'title'=>'满'.$vv['limit'].'元，减免'.$vv['price'].'元',
                                'coupon_id'=>$v['id'],
                                'price'=>$vv['price']
                            ];
                            array_push($arr,$tmp_arr);
                        }
                    }
                }else{
                    $tmp_arr = [
                        'title'=>'减免'.$v['price'].'元',
                        'coupon_id'=>$v['id'],
                        'price'=>$v['price']
                    ];
                    array_push($arr,$tmp_arr);
                }
            }
        }
        return $arr;
    }

    /**
     * Desc:优惠券列表合法校验
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/16 16:13
     * @param $themeid
     */
    public static function couponListDataCheck($themeid)
    {
        $list = self::couponListData($themeid,0,0,0,0,1,0,'',0,0,'','');
        foreach ($list as $K => $v){
            self::couponCheckById($themeid,$v['id']);
        }
    }
    /**
     * Desc:获取优惠券的目标数组
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 20:14
     * @param string $key
     * @param $themeid
     * @return array[]
     */
    public static function couponArrByKey($key='target',$themeid)
    {
        $arr = [];
        $total_sum=0;
        $first = ['title'=>'全部','value'=>0,'total'=>0];
        $arr = self::couponTypeArrByKey($key);
        foreach ($arr as $k =>$v){
            $key_v = $v['value'];
            $sql = " select count(*) as cnt from ".tablename(t_yx_coupon)." where themeid='$themeid'";

            if ($key_v){
                $sql .=  " and $key=$key_v " ;
            }
            $tmp_total =  (int)db_find($sql)['cnt'];
            $arr[$k]['total']=$tmp_total;
            $total_sum+=$tmp_total;
        }
        $first['total']=$total_sum;
        array_unshift($arr,$first);
        return $arr;
    }

    /**
     * Desc:获取优惠券使用数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/24 11:24
     * @param $themeid
     * @param $coupon_id
     * @return mixed
     */
    public static function couponUsedTotal($themeid,$coupon_id,$status=2)
    {
        $sql = " select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid=$themeid and coupon_id=$coupon_id and status=$status";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取用户各种状态的记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 21:26
     * @param string $key
     * @param $themeid
     * @return array
     */
    public static function userCouponArrByKey($key='target',$themeid)
    {
        $arr=[];
        $total_sum =0;
        $first= ['title'=>'全部','value'=>0,'total'=>0];
        $list = self::couponTypeArrByKey($key);
        array_push($arr,$list);
        foreach ($arr as$k => $v){
            $key_v =$v['value'];
            $sql= " select id from ".tablename(t_yx_coupon)." where themeid='$themeid' and '$key'=$key_v ";
            $coupon_list = db_select($sql);
            $tmp_ids = '';
            foreach ($coupon_list as $kk => $vv){
                $tmp_ids .= $vv['id'].',';
            }
            $tmp_ids =rtrim($tmp_ids,',');
            $sum_sql=" select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid=$themeid and coupon_id in (".$tmp_ids." )";
            $item_total= db_find($sum_sql)['cnt'];
            $arr[$k]['total']= $item_total;
            $total_sum+= $item_total;
        }
        $first['total'] =$total_sum;
        array_unshift($arr,$first);
        return $arr;
    }

    /**
     * Desc:获取用户优惠券记录的状态数组
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/16 15:46
     * @param string $key
     * @param $themeid
     * @return array[]
     */
    public static function userCouponFlagArrByKey($key='status',$themeid,$coupon_id=0)
    {
        $arr = [];
        $total_sum=0;
        $first = ['title'=>'全部','value'=>0,'total'=>0];
        $arr = self::couponTypeArrByKey('user_flag_status');
        foreach ($arr as $k =>$v){
            $key_v = $v['value'];
            $sql = " select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid='$themeid'";

            if ($key_v){
                $sql .=  " and $key=$key_v " ;
            }
            if ($coupon_id){
                $sql .=  " and coupon_id=$coupon_id " ;
            }
            $tmp_total =  (int)db_find($sql)['cnt'];
            $arr[$k]['total']=$tmp_total;
            $total_sum+=$tmp_total;
        }
        $first['total']=$total_sum;
        array_unshift($arr,$first);
        return $arr;
    }

    /**
     * Desc:获取用户用户数据或数据数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/5 22:04
     * @param $themeid
     * @param int $target
     * @param int $show_type
     * @param int $used_type
     * @param int $get_type
     * @param int $shangjiaid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param false $count
     * @return int
     */
    public static function userCouponListData($themeid,$target=0,$show_type=0,$used_type=0,$get_type=0,$status=0,$shangjiaid=0,$search='',$page_start=0,
                                              $page_size=10,$start_day='',$end_day='',$record_id=0,$coupon_id=0,$uid=0,$count = false)
    {
        $condition="";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($target){
            $condition .= " and b.target=$target ";
        }
        if ($get_type){
            $condition .= " and b.get_type=$get_type ";
        }
        if ($show_type){
            $condition .= " and b.show_type=$show_type ";
        }
        if ($used_type){
            $condition .= " and b.used_type=$used_type ";
        }
        if ($status){
            $condition .= " and a.status=$status ";
        }
        if ($search){
            $condition .= " AND c.nickname LIKE '".$search."'"." or c.mobile LIKE '".$search."' "." or c.username LIKE '".$search."'";
        }

        if ($coupon_id){
            $condition .= " and a.coupon_id=$coupon_id ";
        }
        if ($record_id && $uid){
            $condition .= " and a.uid=$uid ";
        }else{
            if ($record_id){
                $condition .= " and a.order_id=$record_id ";
            }
            if ($uid){
                $condition .= " and a.uid=$uid ";
            }
        }

        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = " from ".tablename(t_yx_coupon_user_flag)." as a ".
        " left join ".tablename(t_yx_coupon)." as b on a.coupon_id=b.id and b.themeid=a.themeid".
        " left join ".tablename(t_fans)." as c on c.uid=a.uid and c.themeid=a.themeid".
        " left join ".tablename(t_shangjia)." as d on d.id=a.shangjiaid ".
        " left join ".tablename(t_worker)." as e on e.uid=a.workerid ".
        " left join ".tablename(t_worker)." as g on g.uid=a.order_workerid ".
        " left join ".tablename(t_record)." as f on a.order_id=f.id ".
        " where a.themeid='$themeid' ".$condition;
        if ($count){
            return (int)db_fetchcolumn(' select count(*)'.$sql);
        }else{
            $sql = " select a.*,b.target,b.name,b.img,b.get_type,b.show_type,b.used_type,c.nickname,c.avatar,c.username,c.mobile,d.name as shangjia_name,
            e.username as workername,f.status as record_status,g.username as order_workername,f.mobile ".$sql;
            return db_select($sql);
        }
    }
    
    /**
     * Desc:获取用户优惠券列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/6 10:03
     * @param $themeid
     * @param $user_id
     * @param int $coupon_id
     * @return string
     */
    public static function userCouponList($themeid,$user_id,$coupon_id=0)
    {
        $condition =" where a.themeid='$themeid' and a.uid='$user_id' ";
        if ($coupon_id){
            $condition .= " and a.coupon_id='$coupon_id'";
        }
        $condition.= ' order by b.price desc ';
        $sql = " select a.*,b.name,b.img,b.used_type,c.name as shangjianame,d.username as workername,e.status as record_status  from ".tablename(t_yx_coupon_user_flag)." as a".
        " left join ".tablename(t_yx_coupon)." as b on b.id=a.coupon_id and a.themeid=b.themeid ".
        " left join ".tablename(t_shangjia)." as c on c.id=a.shangjiaid ".
        " left join ".tablename(t_worker)." as d on a.workerid=d.uid ".
        " left join ".tablename(t_record)." as e on e.id=a.order_id ";
        $res = db_select($sql.$condition);
        return $res;
    }

    /**
     * Desc:更新用户优惠券记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/6 10:38
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function userCouponEdit($id=0,$where=[],$data)
    {
        if (!$id){
            $item = $insertid = db_insert(t_yx_coupon_user_flag,$data);
        }else{
            $data['updated_at'] = date("Y-m-d H:i:s",time());
            $item = db_update(t_yx_coupon_user_flag,$data,$where);
        }
        return $item;
    }

    /**
     * Desc:获取当前条件下用户可以领取的优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/14 10:05
     * @param $themeid [活动id]
     * @param $config
     * @param $system
     * @param $uid   [uid]
     * @param $worker_id [worker_id]
     * @param int $target  [身份限制 1不限 2团长 3团员]
     * @param int $used_type [预售模式 1不限 2定金 3补款 4全款]
     * @param int $get_type [获取形式 1默认获取 2支付后获取]
     * @return array  ['total_price'=>0,'coupon_ids'=>''] 优惠总金额，优惠券ids 字符串 如 '2,4,9'
     */
    public static function userCouponCanShowItem($themeid,$config,$system,$uid,$worker_id=0,$used_type=0,$get_type=0){
        $list = [];
        //判断异业模式
        $yiye_arr = [101,102,104];
        if (in_array($system['softstyle'],$yiye_arr)){
            //获取当前员工的商家是否有优惠券
            $worker_item = db_get(t_worker,['themeid'=>$themeid,'uid'=>$worker_id]);
        }
        $worker_item = [];

        $now_time=date("Y-m-d H:i:s",time());
        $condition = " and qty>0 and status=1 ";
        //身份限制 1不限 2团长 3团员
//        if ($target){
//            $condition .= " and target='$target' ";
//        }
        //预售模式 1不限 2定金 3补款 4全款 5补款+全款
        if ($used_type){
            $condition .= " and used_type='$used_type' ";
        }
        //获取形式 点击领取 2定金支付后自动发放
        if ($get_type){
            $condition .= " and get_type='$get_type' ";
        }
        //判断用户已经获取到的优惠券 排除
        $user_has_coupon_list = db_getall(t_yx_coupon_user_flag,['themeid'=>$themeid,'uid'=>$uid]);
        $ids = '';
        if ($user_has_coupon_list){
            foreach ($user_has_coupon_list as $k => $v){
                $ids .= $v['coupon_id'].',';
            }
        }
        if ($ids){
            $condition .= " and id not in (".rtrim($ids,',').") ";
        }
        if ($worker_item){
            $shangjid_id = $worker_item['company'];
            if ($shangjid_id){
                //获取商家是否存在优惠券
                $condition = " and shangjiaid='$shangjid_id' ";
            }
            $condition.= 'order by price desc';
            $tmp_sql = " select * from ".tablename(t_yx_coupon)." where themeid='$themeid' " . $condition;
            $list = db_select($tmp_sql);
        }
        if (!$list){
            $condition.= 'order by price desc';
            $tmp_sql = " select * from ".tablename(t_yx_coupon)." where themeid='$themeid'".$condition;
            $list = db_select($tmp_sql);
        }


        if ($list){
            $new_list = [];
            //二次检验优惠券
            foreach ($list as $kk => $vv){
                if (($vv['get_status']==2 && $now_time<=$vv['get_end_time']) || $vv['get_status']==1){
                    array_push($new_list,$vv);
                }
            }
            $list = $new_list;
            //判断系统优惠券使用模式 0 最大金额  1叠加使用
            if ($config['coupon_use_type']==1){
                $total_price = 0;
                $coupon_ids = '';
                foreach ($list as $k => $v){
                    $total_price += floatval($v['price']);
                    $coupon_ids .= $v['id'].',';
                }
                $coupon_ids = rtrim($coupon_ids,',');
                return  ['total_price'=>$total_price,'coupon_ids'=>$coupon_ids];
            }
            return  ['total_price'=>$list[0]['price'],'coupon_ids'=>$list[0]['id']];
        }
        return ['total_price'=>0,'coupon_ids'=>''];
    }

    /**
     * Desc:获取预售模式下用户可领取 支付后自动发放优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/17 16:15
     */
    public static function userCanGetCouponInPresale($themeid,$uid,$system,$config,$workerid)
    {
        $is_presale = CouponModel::isPreSaleSoftMode($system,$config);
        if ($is_presale){
            //判断定金
            if (TIMESTAMP<$config['yukuantime']){
                //支付后自动发放的优惠券数量
                $sql = " select count(*) as cnt from ".tablename(t_yx_coupon)." where themeid=$themeid and get_type=2";
                $total = (int)db_find($sql)['cnt'];
                if ($total>0){
                    $coupon_info = self::userCouponCanShowItem($themeid,$config,$system,$uid,0,3,2);

                    if ($coupon_info && $coupon_info['coupon_ids']){
                        //自动插入用户优惠券领取记录
                        if (strpos($coupon_info['coupon_ids'],',')!==false){
                            $coupon_ids_arr = implode(",",$coupon_info['coupon_ids']);
                        }else{
                            $coupon_ids_arr = [$coupon_info['coupon_ids']];
                        }
                        if ($coupon_ids_arr){
                            foreach ($coupon_ids_arr as $k => $v){
                                $check_user_coupon = db_get(t_yx_coupon_user_flag,['themeid'=>$themeid,'coupon_id'=>$v,'uid'=>$uid]);
                                if (!$check_user_coupon){
                                    //优惠券减库存 增加优惠券领取数
                                    self::couponSubQtyAndAddGetNum($themeid,$v);
                                    $data = ['themeid'=>$themeid,'uid'=>$uid,'workerid'=>$workerid,'coupon_id'=>$v,'status'=>1];
                                    self::userCouponEdit(0,[],$data);
                                    yxlog('用户uid:'.$uid.'支付成功后插入自动发放优惠券','优惠券');
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    /**
     * Desc:用户领取优惠券动作
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/6 14:31
     * @param $themeid
     * @param $worker_id
     * @param $uid
     * @param $coupon_id
     */
    public static function userCouponAutoGet($themeid,$worker_id,$themyrecord,$uid,$coupon_ids,$is_ids=true)
    {
        $coupon_ids_arr = explode(',',$coupon_ids);
        if ($coupon_ids_arr){
            foreach ($coupon_ids_arr as $k => $v){
                $coupon_id = $v;
                $check_coupon_item = self::couponCheckById($themeid,$coupon_id);
                if ($check_coupon_item['code']==1){
                    //判断用户是否已经领取过此优惠券
                    $check_user_coupon = db_get(t_yx_coupon_user_flag,['themeid'=>$themeid,'coupon_id'=>$coupon_id,'uid'=>$uid]);
                    if (!$check_user_coupon){
                        //优惠券减库存 增加优惠券领取数
                        $coupon_res = self::couponSubQtyAndAddGetNum($themeid,$coupon_id);

                        //插入用户优惠券记录
                        $worker_item= db_get(t_worker,['themeid'=>$themeid,'uid'=>$worker_id]);
                        //判断优惠券是否为随机金额
                        $tmp_coupon_item = $check_coupon_item['item'];
                        if ($tmp_coupon_item['price'] && $tmp_coupon_item['max_price'] && $tmp_coupon_item['price'] != $tmp_coupon_item['max_price']){
                            $tmp_coupon_item['price'] = rand($tmp_coupon_item['price'],$tmp_coupon_item['max_price']);
                        }
                        $coupon_price = (float)$tmp_coupon_item['price'];
                        $data = [
                            'uid'=>$uid,'coupon_id'=>$coupon_id,'themeid'=>$themeid,'price'=>$coupon_price
                        ];
                        if ($worker_item){
                            $data['shangjiaid'] = $worker_item['company'];
                            $data['workerid'] = $worker_id;
                        }
                        if ($themyrecord){
                            $data['order_id'] = $themyrecord['id'];
                        }
                        self::userCouponEdit(0,[],$data);
                        yxlog('用户：'.$uid.'；获取优惠券:'.$coupon_id);
                    }else{
                        yxlog('用户：'.$uid.'；已经领取过优惠券:'.$coupon_id);
                    }
                }
            }
        }
    }

    /**
     * Desc:用户自动计算优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/6 16:09
     * @param $themeid
     * @param $uid
     * @param int $coupon_id
     * @return array
     */
    public static function userCouponAutoSum($themeid,$uid,$config,$pay_price=0)
    {
        $system = self::getSystem();
        //判断用户可用的优惠券
        $coupon_id=0;
        $user_coupon_list = self::userCouponList($themeid,$uid,$coupon_id);
        //判断预售
        $is_presale = self::isPreSaleSoftMode($system,$config);
        if ($is_presale){
            //判断存在预售模式下的优惠券
            foreach ($user_coupon_list as $k1 => $v1){
                if ($v1['used_type']!=1){
                    if (TIMESTAMP<$config['yukuantime']){
                        if ($v1['used_type']!=2){
                            unset($user_coupon_list[$k1]);
                        }
                    }else{
                        //补款
                        $is_bukuan = Record::getBukuanByuid($config,$themeid,$uid);
                        if ($is_bukuan['isbukuan']==1 && $v1['used_type']!=3){
                            unset($user_coupon_list[$k1]);
                        }
                        //全款
                        if ($is_bukuan['isbukuan']==2 && $v1['used_type']!=4){
                            unset($user_coupon_list[$k1]);
                        }
                        //补款加全款
                        if ($is_bukuan['isbukuan']>0 && $v1['used_type']!=5){
                            unset($user_coupon_list[$k1]);
                        }
                    }
                }
            }
        }
        if (!$user_coupon_list){
            return ['code'=>0,'msg'=>'用户无优惠券','price'=>0,'coupon_ids'=>''];
        }else{
            //标志位
            $item_flag = ['key'=>0,'price'=>0,'user_coupon_ids'=>''];
            foreach ($user_coupon_list as $k =>$v){
                //未使用状态优惠券
                if ($v['status']==1){
                    //判断优惠券
                    $time = date("Y-m-d H:i:s",time());
                    $coupon_item = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$v['coupon_id']]);
                    if ($config['coupon_use_type']==1){
                        //叠加
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            if ($time>$coupon_item['used_end_time']){
                                //更新用户优惠券
                                $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                $data = ['status'=>3];
                                self::userCouponEdit($coupon_item['id'],$where,$data);
                            }
                            if ($time>$coupon_item['used_start_time'] && $time<$coupon_item['used_end_time']){
                                if (floatval($coupon_item['price'])>0){
                                    $item_flag['key']= $k;
                                    $item_flag['user_coupon_ids'] .= $coupon_item['id'].",";
                                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                        $item_flag['price'] += floatval($v['price']);
                                    }else{
                                        $item_flag['price'] += floatval($coupon_item['price']);
                                    }
                                }
                            }
                        }else{
                            //不限制使用时间
                            if (floatval($coupon_item['price'])>0){
                                $item_flag['key']= $k;
                                $item_flag['user_coupon_ids'] .= $coupon_item['id'].",";
                                if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                    $item_flag['price'] += floatval($v['price']);
                                }else{
                                    $item_flag['price'] += floatval($coupon_item['price']);
                                }
                            }
                        }
                    }elseif ($config['coupon_use_type']==0){
                        //最大一个
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            if ($time>$coupon_item['used_end_time']){
                                yxlog('uid:'.$uid.'；当前时间'.time().'优惠券使用异常信息：'.json_encode($coupon_item));
                                //更新用户优惠券
                                $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                $data = ['status'=>3];
                                self::userCouponEdit($coupon_item['id'],$where,$data);
                            }
                            if ($time>$coupon_item['used_start_time'] && $time<$coupon_item['used_end_time']){
                                if (floatval($coupon_item['price'])>0){
                                    $item_flag['key']= $k;
                                    $item_flag['user_coupon_ids'] = $coupon_item['id'];
                                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                        $item_flag['price'] += floatval($v['price']);
                                    }else{
                                        $item_flag['price'] += floatval($coupon_item['price']);
                                    }
                                    break;
                                }
                            }
                        }else{
                            //不限制使用时间
                            if (floatval($coupon_item['price'])>0){
                                $item_flag['key']= $k;
                                $item_flag['user_coupon_ids'] = $coupon_item['id'];
                                if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                    $item_flag['price'] += floatval($v['price']);
                                }else{
                                    $item_flag['price'] += floatval($coupon_item['price']);
                                }
                                break;
                            }
                        }
                    }else{
                        //阶梯金额
                        $price_info = json_decode($coupon_item['price_info'],true);
                        $sort = array_column($price_info,'price');
                        $new_price_info = array_multisort($sort,SORT_DESC,$price_info);
                        if ($new_price_info && $pay_price){
                            foreach ($price_info as $k1 => $v1)
                            {
                                if ($pay_price>$v1['price']){
                                    $item_flag['key']= $k;
                                    $item_flag['price'] = $v1['price'];
                                    $item_flag['user_coupon_ids'] = $coupon_item['id'];
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            $item_flag['user_coupon_ids'] = rtrim($item_flag['user_coupon_ids'],',');
            if ($item_flag['price']==0){
                return ['code'=>0,'msg'=>'暂无可用优惠券','price'=>0,'user_coupon_ids'=>''];
            }else{
                return  ['code'=>1,'msg'=>'ok','price'=>$item_flag['price'],'user_coupon_ids'=>$item_flag['user_coupon_ids']];
            }
        }
    }

    /**
     * Desc:获取用户优惠券整合信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/14 15:48
     * @param $themeid
     * @param $uid
     * @param $config
     * @return array
     */
    public static function userCouponCanUseInfo($themeid,$uid,$config)
    {
        $theme = Theme::getThemeById($themeid);
        $config = 	Theme::getConfig($themeid);
        $theme_end_time = date('Y-m-d H:i:s',$theme['endtime']);

        //标志位
        $end_time = $theme_end_time;
        $end_total = 0;
        $can_sum_total = 0;
        $end_tips = '';
        $coupon_money = 0;
        $group_min_price = 0;
        $group_max_price = 0;
        
        $user_used = false;
        //判断用户可用的优惠券
        $user_coupon_list = self::userCouponList($themeid,$uid);
        if (!$user_coupon_list){
            return ['end_time'=>'','coupon_money'=>$coupon_money,'end_tips'=>$end_tips];
        }else{
            foreach ($user_coupon_list as $k =>$v){
                if ($v['status']!=2){
                    $can_sum_total+=1;
                    //判断优惠券
                    $time = date("Y-m-d H:i:s",time());
                    $coupon_item = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$v['coupon_id']]);
                    if ($config['coupon_use_type']==1){
                        //叠加
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            //使用时间限制
                            if ($time>$coupon_item['used_end_time']){
                                if ($coupon_item['status']==1){
                                    //更新用户优惠券
                                    $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                    $data = ['status'=>3];
                                    self::userCouponEdit($coupon_item['id'],$where,$data);
                                }
                                $end_total+=1;
                            }
                            if ($time<$coupon_item['used_end_time']){
                                if ($end_time && $coupon_item['used_end_time']<$end_time){
                                    $end_time = $coupon_item['used_end_time'];
                                }
                                if (floatval($coupon_item['price'])>0){
                                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                        $coupon_money += floatval($v['price']);
                                    }else{
                                        $coupon_money += floatval($coupon_item['price']);
                                    }
                                }
                            }
                        }else{
                            //不限制时间
                            if (floatval($coupon_item['price'])>0){
                                if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                    $coupon_money += floatval($v['price']);
                                }else{
                                    $coupon_money += floatval($coupon_item['price']);
                                }
                            }
                        }
                    }
                    elseif ($config['coupon_use_type']==0){
                        //最大一个
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            //使用时间限制
                            if ($time>$coupon_item['used_end_time']){
                                yxlog('uid:'.$uid.'；当前时间'.time().'优惠券使用异常信息：'.json_encode($coupon_item));
                                //更新用户优惠券
                                $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                $data = ['status'=>3];
                                self::userCouponEdit($coupon_item['id'],$where,$data);
                            }
                            if ($time<$coupon_item['used_end_time']){
                                if (floatval($coupon_item['price'])>0){
                                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                        $tmp_coupon_money = floatval($v['price']);
                                    }else{
                                        $tmp_coupon_money = floatval($coupon_item['price']);
                                    }
                                    if ($tmp_coupon_money>$coupon_money){
                                        $coupon_money = $tmp_coupon_money;
                                        if ($coupon_item['used_end_time']<$end_time){
                                            $end_time = $coupon_item['used_end_time'];
                                        }
                                    }
                                }
                            }
                        }else{
                            //不限制时间
                            if (floatval($coupon_item['price'])>0){
                                if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                    $tmp_coupon_money = floatval($v['price']);
                                }else{
                                    $tmp_coupon_money = floatval($coupon_item['price']);
                                }
                                if ($tmp_coupon_money>$coupon_money){
                                    $coupon_money = $tmp_coupon_money;
                                }
                            }
                        }
                    }else{
                        //阶梯价格
                        $item_price_info = json_decode($coupon_item['price_info'],true);
                        if($item_price_info){
                            $tmp_group_key = array_column($item_price_info,'price');
                            array_multisort($tmp_group_key,SORT_DESC,$item_price_info);
                            $new_item_price_arr_length = count($item_price_info)-1;
                            $group_min_price = $item_price_info[$new_item_price_arr_length]['price'];
                            $group_max_price = 0;
                            foreach ($item_price_info as $k1 => $v1){
                                $group_max_price += floatval($v1['price']);
                            }
                            if (floatval($coupon_money) < floatval($group_max_price)) {
                                $coupon_money = $group_max_price;
                            }
                        }
                    }
                }else{
                    $coupon_item = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$v['coupon_id']]);
                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price']!=$coupon_item['max_price']){
                        if (floatval($v['price'])>0){
                            $coupon_money += floatval($v['price']);
                        }
                    }else{
                        if (floatval($coupon_item['price'])>0){
                            $coupon_money += floatval($coupon_item['price']);
                        }
                    }
                    $end_tips ='已使用';
                    $end_time='';
                }
            }
        }
        if ($config['coupon_use_type']==1){
            //叠加
            if ($end_total==$can_sum_total){
                $coupon_money = 0;
                $end_tips ='已过期';
                $end_time='';
            }
        }elseif ($config['coupon_use_type']==0){
            //最大
            if ($coupon_money==0){
                $coupon_money = 0;
                $end_tips ='';
                $end_time= '';
            }
        }
        return ['end_time'=>$end_time,'coupon_money'=>$coupon_money,'end_tips'=>$end_tips];
    }

    /**
     * Desc:判断用户优惠券信息（使用条件）
     * Author:cbw
     * Time: 2023/8/9 14:35
     * @param $themeid
     * @param $uid
     * @param $config
     * @return array
     */
    public static function userCouponCanUseInfoNew($themeid,$uid,$config,$system)
    {
        $theme = Theme::getThemeById($themeid);
        $config = 	Theme::getConfig($themeid);
        $theme_end_time = date('Y-m-d H:i:s',$theme['endtime']);

        //标志位
        $end_time = $theme_end_time;
        $end_total = 0;
        $can_sum_total = 0;
        $end_tips = '';
        $coupon_money = 0;
        $group_min_price = 0;
        $group_max_price = 0;
        //判断用户可用的优惠券
        $user_coupon_list = self::userCouponList($themeid,$uid);
        //判断预售
        $is_presale = self::isPreSaleSoftMode($system,$config);
        if ($is_presale){
            //判断存在预售模式下的优惠券
            foreach ($user_coupon_list as $k1 => $v1){
                if ($v1['used_type']!=1){
                    if (TIMESTAMP<$config['yukuantime']){
                        if ($v1['used_type']!=2){
                            unset($user_coupon_list[$k1]);
                        }
                    }else{
                        //补款
                        $is_bukuan = Record::getBukuanByuid($config,$themeid,$uid);
                        if ($is_bukuan['isbukuan']==1 && $v1['used_type']!=3){
                            unset($user_coupon_list[$k1]);
                        }
                        //全款
                        if ($is_bukuan['isbukuan']==2 && $v1['used_type']!=4){
                            unset($user_coupon_list[$k1]);
                        }
                        //补款加全款
                        if ($is_bukuan['isbukuan']>0 && $v1['used_type']!=5){
                            unset($user_coupon_list[$k1]);
                        }
                    }
                }
            }
        }
        if (!$user_coupon_list){
            return ['end_time'=>'','coupon_money'=>$coupon_money,'end_tips'=>$end_tips];
        }else{
            foreach ($user_coupon_list as $k =>$v){
                if ($v['status']!=2){
                    $can_sum_total+=1;
                    //判断优惠券
                    $time = date("Y-m-d H:i:s",time());
                    $coupon_item = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$v['coupon_id']]);
                    if ($config['coupon_use_type']==1){
                        //叠加
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            //使用时间限制
                            if ($time>$coupon_item['used_end_time']){
                                if ($coupon_item['status']==1){
                                    //更新用户优惠券
                                    $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                    $data = ['status'=>3];
                                    self::userCouponEdit($coupon_item['id'],$where,$data);
                                }
                                $end_total+=1;
                            }
                            if ($time>$coupon_item['used_start_time'] && $time<$coupon_item['used_end_time']){
                                if ($end_time && $coupon_item['used_end_time']<$end_time){
                                    $end_time = $coupon_item['used_end_time'];
                                }
                                if (floatval($coupon_item['price'])>0){
                                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                        $coupon_money += floatval($v['price']);
                                    }else{
                                        $coupon_money += floatval($coupon_item['price']);
                                    }
                                }
                            }
                        }else{
                            //不限制时间
                            if (floatval($coupon_item['price'])>0){
                                if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                    $coupon_money += floatval($v['price']);
                                }else{
                                    $coupon_money += floatval($coupon_item['price']);
                                }
                            }
                        }
                    }
                    elseif ($config['coupon_use_type']==0){
                        //最大一个
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            //使用时间限制
                            if ($time>$coupon_item['used_end_time']){
                                yxlog('uid:'.$uid.'；当前时间'.time().'优惠券使用异常信息：'.json_encode($coupon_item));
                                //更新用户优惠券
                                $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                $data = ['status'=>3];
                                self::userCouponEdit($coupon_item['id'],$where,$data);
                            }
                            if ($time>$coupon_item['used_start_time'] && $time<$coupon_item['used_end_time']){
                                if (floatval($coupon_item['price'])>0){
                                    if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                        $tmp_coupon_money = floatval($v['price']);
                                    }else{
                                        $tmp_coupon_money = floatval($coupon_item['price']);
                                    }
                                    if ($tmp_coupon_money>$coupon_money){
                                        $coupon_money = $tmp_coupon_money;
                                        if ($coupon_item['used_end_time']<$end_time){
                                            $end_time = $coupon_item['used_end_time'];
                                        }
                                    }
                                }
                            }
                        }else{
                            //不限制时间
                            if (floatval($coupon_item['price'])>0){
                                if ($coupon_item['price'] && $coupon_item['max_price'] && $coupon_item['price'] !=$coupon_item['max_price']){
                                    $tmp_coupon_money = floatval($v['price']);
                                }else{
                                    $tmp_coupon_money = floatval($coupon_item['price']);
                                }
                                if ($tmp_coupon_money>$coupon_money){
                                    $coupon_money = $tmp_coupon_money;
                                }
                            }
                        }
                    }else{
                        //阶梯价格
                        //判断使用时间
                        if ($coupon_item['show_type']==2){
                            //使用时间限制
                            if ($time>$coupon_item['used_end_time']){
                                if ($coupon_item['status']==1){
                                    //更新用户优惠券
                                    $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                                    $data = ['status'=>3];
                                    self::userCouponEdit($coupon_item['id'],$where,$data);
                                }
                                $end_total+=1;
                            }
                            if ($time>$coupon_item['used_start_time'] && $time<$coupon_item['used_end_time']){
                                if ($end_time && $coupon_item['used_end_time']<$end_time){
                                    $end_time = $coupon_item['used_end_time'];
                                }
                                $item_price_info = json_decode($coupon_item['price_info'],true);
                                if($item_price_info){
                                    $tmp_group_key = array_column($item_price_info,'price');
                                    array_multisort($tmp_group_key,SORT_DESC,$item_price_info);
                                    $new_item_price_arr_length = count($item_price_info)-1;
                                    $group_min_price = $item_price_info[$new_item_price_arr_length]['price'];
                                    $group_max_price = (float)$item_price_info[0]['price'];
//                                    $group_max_price = 0;
//                                    foreach ($item_price_info as $k1 => $v1){
//                                        $group_max_price += floatval($v1['price']);
//                                    }
                                    if (floatval($coupon_money) < floatval($group_max_price)) {
                                $coupon_money = $group_max_price;
                            }
                                }
                            }
                        }else{
                            //不限制时间
                            $item_price_info = json_decode($coupon_item['price_info'],true);
                            if($item_price_info){
                                $tmp_group_key = array_column($item_price_info,'price');
                                array_multisort($tmp_group_key,SORT_DESC,$item_price_info);
                                $new_item_price_arr_length = count($item_price_info)-1;
                                $group_min_price = $item_price_info[$new_item_price_arr_length]['price'];
                                $group_max_price = (float)$item_price_info[0]['price'];
//                                $group_max_price = 0;
//                                foreach ($item_price_info as $k1 => $v1){
//                                    $group_max_price += floatval($v1['price']);
//                                }
                                if (floatval($coupon_money) < floatval($group_max_price)) {
                                $coupon_money = $group_max_price;
                            }
                            }
                        }
                    }
                }
            }
        }
        if ($config['coupon_use_type']==1){
            //叠加
            if ($end_total==$can_sum_total){
                $coupon_money = 0;
                $end_tips ='已过期';
                $end_time='';
            }
        }elseif ($config['coupon_use_type']==0){
            //最大
            if ($coupon_money==0){
                $coupon_money = 0;
                $end_tips ='';
                $end_time= '';
            }
        }
        return ['end_time'=>$end_time,'coupon_money'=>$coupon_money,'end_tips'=>$end_tips];
    }

    /**
     * Desc:绑定优惠券与用户订单关系
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/15 18:43
     * @param $themeid
     * @param $recordid
     * @param $user_coupon_ids
     */
    public static function apiInsertUserInfo($themeid,$recordid,$user_coupon_ids,$coupon_price=0)
    {
        yxlog('$user_coupon_ids:'.$user_coupon_ids);
        yxlog('$coupon_price:'.$coupon_price);
        if ($user_coupon_ids){
            $themyrecord = db_get(t_record,['themeid'=>$themeid,'id'=>$recordid]);
            if ($themyrecord){
                $user_coupon_ids_arr = explode(',',$user_coupon_ids);
                yxlog($user_coupon_ids_arr,'用户使用优惠券');
                foreach ($user_coupon_ids_arr as $k => $v){
                    //更新用户优惠券
                    $where = ['themeid'=>$themeid,'uid'=>$themyrecord['uid'],'coupon_id'=>$v];
                    $data = ['order_id'=>$recordid];
                    if ($coupon_price){
                        $data['price'] = $coupon_price;
                    }
                    self::userCouponEdit($v,$where,$data);

                }
            }

        }
    }

    /**
     * Desc:支付成功后的更新用户状态
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/16 08:17
     * @param $themeid
     * @param $uid
     * @param $recordid
     */
    public static function payRollback($themeid,$uid,$recordid,$config,$system)
    {
        //用户优惠券记录
        $user_coupon_flags = db_getall(t_yx_coupon_user_flag,['themeid'=>$themeid,'order_id'=>$recordid,'uid'=>$uid]);
        if ($user_coupon_flags){
            foreach ($user_coupon_flags as $k => $v){
                if ($v['status']==1){
                    //更新优惠券使用量
                    $coupon_item = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$v['coupon_id']]);
                    $data = ['use_num'=>$coupon_item['use_num']+1];
                    $update_coupon_item = self::couponEditItem($coupon_item['id'],$data,['themeid'=>$themeid]);
                    $order_item = db_get(t_record,['themeid'=>$themeid,'id'=>$recordid,'uid'=>$uid]);
                    //更新用户优惠券记录状态
                    $where = ['themeid'=>$themeid,'uid'=>$uid,'coupon_id'=>$coupon_item['id']];
                    $data  = ['status'=>2,'order_workerid'=>$order_item['workerid']];
                    if ($system['selecet_pay']==1 && $config['shops'] && ($config['shopstype']==3 || $config['shopstype']==4)){
                        $realy_coupon_price = self::getSelectPayOrderUseCouponPrice($order_item,$config,$coupon_item);
                        if ($realy_coupon_price){
                            $data['price'] = $realy_coupon_price;
                        }
                    }
                    self::userCouponEdit($coupon_item['id'],$where,$data);
                    //判断是否无限购买
                    if (!$config['wuxian']){
                        //判断是否为使用最大 其他获取的优惠券记录为失效
//                if ($config['coupon_use_type']==0){
//                    $where1 = ['themeid'=>$themeid,'status'=>1];
//                    $data1 = ['status'=>3];
//                    self::userCouponEdit(9999999,$where1,$data1);
//                }
                    }
                    //判断预售
                    $is_presale = self::isPreSaleSoftMode($system,$config);
                    if ($is_presale && !$config['coupon_use_type']){
                        //最大模式
                        if (TIMESTAMP>=$config['yukuantime']){
                            //补款+全款 设置其他为失效
//                    $where1 = ['themeid'=>$themeid,'status'=>1];
//                    $data1 = ['status'=>3];
//                    self::userCouponEdit(9999999,$where1,$data1);
                        }
                    }
                }
            }
        }

    }

    /**
     * Desc:获取用户的优惠券记录数 【无任何条件】
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/14 15:09
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function userCouponFlagTotal($themeid,$uid,$status=0,$order_id=0)
    {
        $condition = '';
        if ($status){
            $condition .= " and status=$status";
        }
        if ($order_id){
            $condition .= " and order_id=$order_id";
        }
        $sql = " select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid='$themeid' and uid='$uid'".$condition;
        return (int)db_find($sql)['cnt'];
    }

    /**
     * Desc:获取优惠券记录以及优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/17 11:26
     * @param $themeid
     * @param $uid
     * @param int $status
     * @param int $order_id
     * @return mixed
     */
    public static function userCouponFlagInfo($themeid,$uid,$status=0,$order_id=0)
    {
        $total_coupon_price = 0;
        $total_coupon_name = '';
        $condition = '';
        if ($status){
            $condition .= " and a.status=$status";
        }
        if ($order_id){
            $condition .= " and a.order_id=$order_id";
        }
        $sql = " select a.order_id,a.coupon_id,a.status,b.price,b.name as coupon_name  from ".tablename(t_yx_coupon_user_flag)." as a ".
            " left join ".tablename(t_yx_coupon)." as b on b.id=a.coupon_id and b.themeid=a.themeid".
            " where a.themeid=$themeid and a.uid=$uid".$condition;
        $list =db_select($sql);
        foreach ($list as $k => $v){
            $total_coupon_price+=$v['price'];
            $total_coupon_name.=$v['coupon_name'].';';
        }
        return ['price'=>$total_coupon_price,'coupon_name'=>$total_coupon_name];
    }

    /**
     * Desc:获取用户优惠券列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/14 17:48
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function userCouponFlagList($themeid,$uid,$config)
    {
        global $_G,$_P,$_S,$_C;
        $sql = " select a.id,a.price as uf_price,a.uid,a.coupon_id,a.status,b.price,b.max_price,b.price_info,b.used_end_time,b.used_start_time,b.used_type,b.show_type from ".tablename(t_yx_coupon_user_flag)." as a".
            " left join ".tablename(t_yx_coupon)." as b on a.coupon_id=b.id and b.themeid=a.themeid ".
            " where a.themeid=$themeid and a.uid=$uid order by price desc";
        $user_list = db_select($sql);
        $top = [];
        $is_not_max = false;
        $user_offline_order = db_get(t_record,['themeid'=>$themeid,'uid'=>$uid,'status'=>3]);
        $is_presale = self::isPreSaleSoftMode($_S,$config);
        $get_coupon_cannot_use = false;
        if ($user_offline_order && !$is_presale){
            $get_coupon_cannot_use = true;
        }
        foreach ($user_list as $k => $v){
            //判断使用时间
            $time = date("Y-m-d H:i:s",time());
            $btm_txt = '';
            $action = '';
            $diy_jump = '';
            $total_amount = '';
            $tips = '';
            $is_offline = false;

            $last_tips = '';
            if ($v['used_type']==2){
                $last_tips = '(仅限占位使用)';
            }elseif ($v['used_type']==3){
                $last_tips = '(仅限补款使用)';
            }elseif ($v['used_type']==4){
                $last_tips = '(仅限全款使用)';
            }elseif ($v['used_type']==5){
                $last_tips = '(仅限补款、全款使用)';
            }
            if ($v['price']>$config['groupprice'] && $v['price']>$config['primeprice'] && $v['price']>$config['joinfee'] && $v['price']>$config['yukuan']){
                $last_tips = $config['coupon_offline_tips'];
                $is_offline = true;
            }

            $tmp_icon = 'https://css2020.yixuan.net/2020css/plugin/lottery/images/bag.png';
            if ($config['coupon_use_type']==0){
                //最大模式
                if ($k==0){
                    $total_amount = '可使用';
                    $diy_jump = ['url'=>992,'function'=>'bottomButton','options'=>0];
                    $btm_txt = '立即使用';
                    if ($time<$v['used_start_time']){
                        $total_amount =  '待生效';
                        $btm_txt = '';
                        $is_not_max = true;
                        $tips = '生效时间:'.date("Y/m/d H:i",strtotime($v['used_start_time']));
                    }
                    if ($v['show_type']==2 && $time>$v['used_end_time']){
                        $total_amount = $btm_txt = '已过期';
                        $tips = '当前优惠券过期失效';
                    }
                    if ($v['status']==2){
                        $total_amount = $btm_txt = '已使用';
                        $tips = '最大金额优惠券'.$last_tips;
                    }
                    if ($is_offline){
                        $total_amount = $config['coupon_offline_right_txt_top'];
                        $btm_txt = $config['coupon_offline_btn'];
                    }else{
                        if ($get_coupon_cannot_use){
                            $total_amount = $btm_txt = '不可用';
                            $tips = '当前优惠券仅对线上支付生效';
                        }
                    }

                }else{
                    if ($is_not_max){
                        $total_amount = '可使用';
                        $diy_jump = ['url'=>992,'function'=>'bottomButton','options'=>0];
                        $btm_txt = '立即使用';
                        if ($time<$v['used_start_time']){
                            $total_amount =  '待生效';
                            $btm_txt = '';
                            $is_not_max = true;
                            $tips = '生效时间:'.date("Y/m/d H:i",strtotime($v['used_start_time']));
                        }
                    }
                    if ($v['status']==2){
                        $total_amount = $btm_txt = '已使用';
                    }
                    if ($v['status']==3){
                        $total_amount =  '已失效';
                        $tips = '已使用最大金额优惠券，当前优惠券失效';
                    }
                    if ($is_offline){
                        $total_amount = $config['coupon_offline_right_txt_top'];
                        $btm_txt = $config['coupon_offline_btn'];
                    }else{
                        if ($get_coupon_cannot_use){
                            $total_amount = $btm_txt = '不可用';
                            $tips = '当前优惠券仅对线上支付生效';
                        }
                    }

                }
            }
            elseif ($config['coupon_use_type']==1){
                //叠加模式
                if (count($user_list)>1){
                    $total_amount = '可叠加';
                    $tips = '多个优惠券可叠加使用'.$last_tips;
                    $diy_jump = ['url'=>992,'function'=>'bottomButton','options'=>0];
                    $btm_txt = '立即使用';
                }
                if ($v['show_type']==2 && $time>$v['used_end_time']){
                    $total_amount = $btm_txt = '已过期';
                    $tips = '当前优惠券已过期';
                }
                if ($v['status']==2){
                    $total_amount = $btm_txt = '已使用';
                    $tips = '当前优惠券已使用';
                }
                if ($v['status']==3){
                    $total_amount = $btm_txt =  '已失效';
                    $tips = '当前优惠券已失效';
                }
            }
            else{
                $item_list = json_decode($v['price_info'],true);
                if ($item_list){
                    foreach ($item_list as $k1 => $v1){
                        if ($v['show_type']==1){
                            $tips = '满'.$v1['limit'].'元，减免'.$v1['price'].'元'.$last_tips;
                        }else{
                            if ($time>$v['used_end_time']){
                                $total_amount = $btm_txt = '已过期';
                                $tips = '当前优惠券已过期';
                            }elseif ($time<>$v['used_start_time']){
                                $total_amount = $btm_txt =  '待生效';
                                $tips = '生效时间:'.date("Y/m/d H:i",strtotime($v['used_start_time']));
                            }
                        }


                        $tmp_arr = [
                            'total_amount'=> $v1['price'].'元',
                            'amount'=> $total_amount,
                            'icon'=> $tmp_icon,
                            'tips'=> $tips,
                            'btm_txt'=> $btm_txt ,
                            'action'=> $action,
                            'target_id'=> $v['coupon_id'],
                            'diy_jump'=>$diy_jump,
                        ];
                        array_push($top,$tmp_arr);
                    }
                }
            }

            if ($config['coupon_use_type']!=3){
                $tmp_price = $v['price'];
                if ($v['price'] && $v['max_price'] && $v['price']!=$v['max_price']){
                    $tmp_price= $v['uf_price'];
                }
                $center_item = [
                    'total_amount'=> $tmp_price.'元',
                    'amount'=> $total_amount,
                    'icon'=> $tmp_icon,
                    'tips'=> $tips.$last_tips,
                    'btm_txt'=> $btm_txt ,
                    'action'=> $action,
                    'target_id'=> $v['coupon_id'],
                    'diy_jump'=>$diy_jump,
                ];
                array_push($top,$center_item);
            }
        }
        return $top;
    }

    /**
     * Desc:判断是否开启预售模式
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/14 13:42
     * @param $system
     * @param $config
     * @return bool
     */
    public static function isPreSaleSoftMode($system,$config)
    {
        $is_presale = false;
        if ($system['ispresale']==1 && $config['yukuan']>0){
            $is_presale = true;
        }
        return $is_presale;
    }

    /**
     * Desc:协议内容替换
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/16 13:14
     * @param $themeid
     * @param $config
     * @param $system
     * @param $uid
     * @return string|string[]
     */
    public static function getUserUseCouponTips($themeid,$config,$system,$uid)
    {
        //是否开启优惠券
        if ($system['yx_coupon']==1){
            //判断设置了协议替换内容
            if ($config['coupon_txt_tmp']){
                //判断用户存在优惠券
                $user_coupon_res = CouponModel::userCouponCanUseInfoNew($themeid,$uid,$config,$system);
                if ($user_coupon_res && $user_coupon_res['coupon_money']>0){
                    //开始替换文本
                    return str_replace('#fee',$user_coupon_res['coupon_money'],$config['coupon_txt_tmp']);
                }
            }
        }
        return '';
    }

    /**
     * Desc:获取用户使用优惠券抵扣总额
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/16 14:03
     * @param $record_id
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserUsedCouponAmountTotal($record_id,$themeid,$uid)
    {
        $sql = " select sum(a.price) as coupon_amount,a.* from ".tablename(t_yx_coupon_user_flag)." as a ".
        " left join ".tablename(t_yx_coupon)." as b on a.coupon_id=b.id and a.themeid=b.themeid".
        " where a.themeid=$themeid and a.uid=$uid and a.order_id=$record_id and a.status=2";
        return db_find($sql)['coupon_amount'];
    }

    /**
     * Desc:获取当前时间前的出入用户uid的所有使用优惠券的总金额
     * Author:cbw
     * Time: 2023/8/14 02:38
     * @param $themeid
     * @param $uid 第一个uid
     * @param $uid_other 第二个uid
     * @return mixed 返回的是非格式化的金额 调用的时候（float）
     */
    public static function getUserUsedCouponAmountByUIDAndTime($themeid,$uid,$uid_other='')
    {
        $condition = "  and a.uid=$uid ";
        if ($uid && $uid_other && $uid!=$uid_other){
            $condition = " and (a.uid=$uid or a.uid=$uid_other) ";
        }
        $temp_sql = " select sum(a.price) as coupon_amount,a.* from ".tablename(t_yx_coupon_user_flag)." as a ".
            " left join ".tablename(t_yx_coupon)." as b on a.coupon_id=b.id and a.themeid=b.themeid".
            " where a.themeid=$themeid and a.status=2 ".$condition;
        return db_find($temp_sql)['coupon_amount'];
    }

    /**
     * Desc:判断用户是否存在使用的优惠券记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/16 14:36
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserIsUsedCoupon($themeid,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid='$themeid' and uid='$uid' and status=2";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取用户的可补发的优惠券
     * Author:cbw
     * Time: 2023/8/11 05:30
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function getUserCanUserCouponItems($themeid,$uid)
    {
        global $_G,$_P,$_S,$_C;
        $format_coupon_list = [];
        //获取后台设置的可用的优惠券
        $coupon_list = db_getall(t_yx_coupon,['themeid'=>$themeid,'status'=>1,'qty >'=>0]);
        if ($coupon_list){
            foreach ($coupon_list as $k => $val){
                //当前用户没有领取的
                $check_user_has_coupon = db_get(t_yx_coupon_user_flag,['themeid'=>$themeid,'coupon_id'=>$val['id'],'uid'=>$uid]);
                if (!$check_user_has_coupon){
                    //未限制使用时间或限制时间未达到使用时间的优惠券
                    if ($val['show_type']==1 || ($val['show_type']==2 && TIMESTAMP<$val['used_end_time'])){
                        array_push($format_coupon_list,$val);
                    }
                }
            }
        }
        //二次校验 以及预售模式下条件是否满足
        $is_presale = self::isPreSaleSoftMode($_S,$_C);
        if ($is_presale && $format_coupon_list){
            foreach ($format_coupon_list as $kk => $vv){
                //定金使用
                if ($vv['used_type']==2){
                    $themyrecord = db_get(t_record,['themeid'=>$themeid,'uid'=>$uid,'status'=>1]);
                    if ($themyrecord || TIMESTAMP>=$_C['yukuantime']){
                        unset($format_coupon_list[$kk]);
                    }
                }
                //补款
                if ($vv['used_type']==3){
                    $is_bukuan = Record::getBukuanByuid($_C,$themeid,$uid);
                    if ($is_bukuan!=1){
                        unset($format_coupon_list[$kk]);
                    }
                }
                //全款
                if ($vv['used_type']==4){
                    $is_bukuan = Record::getBukuanByuid($_C,$themeid,$uid);
                    if ($is_bukuan!=2){
                        unset($format_coupon_list[$kk]);
                    }
                }
                //补款+全款
                if ($vv['used_type']==5){
                    $is_bukuan = Record::getBukuanByuid($_C,$themeid,$uid);
                    if ($is_bukuan<=0){
                        unset($format_coupon_list[$kk]);
                    }
                }
            }
        }
        return $format_coupon_list;
    }

    /**
     * Desc:格式化优惠券数量 名称、id\领取、使用数
     * Author:cbw
     * Time: 2023/8/14 05:35
     * @param $themeid
     * @return array
     */
    public static function getFormatCouponInfo($themeid)
    {
        $format_coupon_data = [];
        $total_get_num = 0;
        $total_use_num = 0;
        $coupon_list = db_getall(t_yx_coupon,['themeid'=>$themeid]);
        foreach ($coupon_list as $k => $v){
            $get_num_sql = " select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid=$themeid and status=1 and coupon_id=".$v['id'];
            $use_num_sql = " select count(*) as cnt from ".tablename(t_yx_coupon_user_flag)." where themeid=$themeid and status=2 and coupon_id=".$v['id'];
            $get_num = db_find($get_num_sql)['cnt'];
            $use_num = db_find($use_num_sql)['cnt'];
            $tmp_arr = [
                'name'=>$v['name'],
                'id'=>$v['id'],
                'get_num'=>$get_num,
                'use_num'=>$use_num
            ];
            $total_get_num+=$get_num;
            $total_use_num+=$use_num;
            array_push($format_coupon_data,$tmp_arr);
        }
        array_unshift($format_coupon_data,['name'=>'全部','id'=>0,'get_num'=>$total_get_num,'use_num'=>$total_use_num]);
        return $format_coupon_data;
    }

    /**
     * Desc:获取阶梯价格模式下订单抵扣的区间金额
     * Author:cbw
     * Time: 2023/8/16 10:24
     * @param $record
     * @param $config
     * @param $coupon_item
     * @return int|mixed
     */
    public static function getSelectPayOrderUseCouponPrice($record,$config,$coupon_item)
    {
        $use_coupon_price = 0;
        $pay_amount = $record['fee'];
        $config_shops_price = $config['shops_price'];
        $config_shops_price_guding = $config['shops_price_guding'];
        $config_option = $config['option'];
        $config_gudingoptions = $config['gudingoptions'];
        $diff_price = 0;
        $record_option_arr = explode('|',$record['option']);
        foreach ($record_option_arr as $k => $v){
            foreach ($config_option as $k1 => $v1){
                if ($v==$v1){
                    $diff_price+= (float)$config_shops_price[$k1];
                }
            }
            foreach ($config_gudingoptions as $k2 => $v2){
                if ($v==$v2){
                    $diff_price+= (float)$config_shops_price_guding[$k2];
                }
            }
        }
        $total_amount = $pay_amount+$diff_price;
        if ($total_amount>0){
            $item_price_info = json_decode($coupon_item['price_info'],true);
            if($item_price_info){
                $tmp_group_key = array_column($item_price_info,'price');
                array_multisort($tmp_group_key,SORT_DESC,$item_price_info);
                foreach ($item_price_info as $kk1 => $vv1){
                    if ($vv1['limit']>=$total_amount){
                        $use_coupon_price = $vv1['price'];
                    }
                }
            }
        }
        return $use_coupon_price;
    }



























































}